<?php
declare(strict_types=1);

namespace app\curd\command;

use think\helper\Str;
use think\console\Input;
use think\console\Output;
use think\console\Command;
use think\console\input\Argument;

class Ddv extends Command
{
    protected $type;

    protected function configure()
    {
        // 指令配置
        $this->setName('xcurd:v')
            ->addArgument('name', Argument::OPTIONAL, "格式：应用名@控制器名 控制器名采用驼峰法（首字母大写）")
            ->setDescription('生成CURD视图，格式：app@Controller 命名采用驼峰法（首字母大写）');
    }

    protected function getStubindex(): string
    {
        $stubPath = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR;

        return $stubPath . 'view' . DIRECTORY_SEPARATOR . 'index.stub';
    }
    protected function getStubform(): string
    {
        $stubPath = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR;

        return $stubPath . 'view' . DIRECTORY_SEPARATOR . 'form.stub';
    }

    protected function execute(Input $input, Output $output)
    {
        $name = trim($input->getArgument('name'));
        [$app, $name] = explode('@', $name);

        $name = Str::snake($name);

        $indexpathname = $this->app->getBasePath(). DIRECTORY_SEPARATOR . $app . '/view/' . $name . '/index.html';
        $formpathname = $this->app->getBasePath(). DIRECTORY_SEPARATOR . $app . '/view/' . $name . '/form.html';

        $output->writeln('<info>Checking paths:</info>');
        $output->writeln('<info>Index Path: ' . $indexpathname . '</info>');
        $output->writeln('<info>Form Path: ' . $formpathname . '</info>');

        if (is_file($indexpathname) || is_file($formpathname)) {
            $output->writeln('<error> CURD视图已存在，请删除index和form后再尝试生成!</error>');
            return false;
        }

        if (!is_dir(dirname($indexpathname))) {
            mkdir(dirname($indexpathname), 0755, true);
        }

        if (!is_dir(dirname($formpathname))) {
            mkdir(dirname($formpathname), 0755, true);
        }

        $stubindex = file_get_contents($this->getStubindex());
        $stubform = file_get_contents($this->getStubform());

        file_put_contents($indexpathname, $stubindex);
        file_put_contents($formpathname, $stubform);

        $output->writeln('<info>' . $indexpathname . ' 列表试图已生成.</info>');
        $output->writeln('<info>' . $formpathname . ' 表单视图已生成.</info>');
    }

}
